
//新版基础函数
var f = {
    init:function() {
        log("程序初始化成功")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (percentX, percentY, percentX1, percentY1, times) {
        // 获取设备的宽度和高度
        const width = device.width;
        const height = device.height;

        // 将百分比转换为实际坐标
        const x = Math.round(width * percentX);
        const y = Math.round(height * percentY);
        const x1 = Math.round(width * percentX1);
        const y1 = Math.round(height * percentY1);

        // 执行滑动操作
        swipe(x, y, x1, y1, times);
        sleep(1000);
    }
}
f.init()


var appInfo = {}
var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);

// 新增一个 post 方法，请求头为 json 格式，只需要传入 data 参数
f.postJson = function(data) {
    let url = 'http://api.wenfree.cn/?s=App.Autojs_Xhs.Add'
    var headers = {
        "Content-Type": "application/json; charset=utf-8"
    };

    
    log(url,JSON.stringify(data))
    var res = http.postJson(url, data, headers);
    var data = res.body.string();
    if(data){
        // 
        log('postJson', data);
        data = JSON.parse(data)
        appInfo.page_id = data.data.data.id
        log('appInfo.page_id', appInfo.page_id)
        return data;
    }
};
// 新增一个 post 方法，请求头为 json 格式，只需要传入 data 参数
f.postJsonc = function(data) {
    let url = 'http://api.wenfree.cn/?s=App.Autojs_Xhs.Addc'
    var headers = {
        "Content-Type": "application/json; charset=utf-8"
    };

    log(url,JSON.stringify(data))
    var res = http.postJson(url, data, headers);
    var data = res.body.string();
    if(data){
        log(data)
        return data;
    }
};

// 解析小红书短链接为真实链接
f.getRealUrl = function(shortUrl) {
    // 接口地址
    let url = 'https://api.wenfree.cn/Autojs_Xhs/realurl';
    // 请求参数
    let data = {
        "url": shortUrl
    };
    // 请求头
    var headers = {
        "Content-Type": "application/json; charset=utf-8"
    };

    log("请求解析短链接:", shortUrl);
    var res = http.postJson(url, data, headers);
    var responseData = res.body.string();
    log("解析结果:", responseData);

    if (responseData) {
        try {
            // 解析JSON响应
            let jsonData = JSON.parse(responseData);
            // 检查是否成功
            if (jsonData.code === 200 && jsonData.data && jsonData.data.real_url) {
                return jsonData.data.real_url;
            } else {
                log("解析失败:", jsonData.message || "未知错误");
                return null;
            }
        } catch (e) {
            log("解析响应失败:", e.message);
            return null;
        }
    }
    return null;
}



// //批查打印app参数
function printAll(ways) {
    if (!ways) {
        ways = 'className'
    }
    if (ways = 'className') {
        var all_Info = classNameMatches(/.*/).find();
    } else
        if (ways == 'text') {
            var all_Info = textMatches(/.*/).find();
        } else
            if (ways == 'id') {
                var all_Info = idMatches(/.*/).find();
            } else {
                eval('var all_Info = ' + ways + '.find();')
            }

    if (all_Info) {
        for (var i = 0; i < all_Info.length; i++) {
            var d = all_Info[i];
            log(i, d.id(), d.text(), "desc:" + d.desc(), '"className":"' + d.className() + '"',
                "clickable->" + d.clickable(), 'selected->' + selected(), "depth->" + d.depth(),
                d.bounds().centerX(), d.bounds().centerY())
        }
    } else {
        log('没有找到任何相关的节点')
    }
}

function getAllText(obj){
    const textInfo = {};
    try {
        if( obj.text() ){
            textInfo['text'] = obj.text()
        }
        if( obj.desc() ){
            textInfo['desc'] = obj.desc()
        }
        if( obj.id() ){
            textInfo['id'] = obj.id()
        }
        if( obj.children().length > 0 ){
            textInfo.child = []
            for (let i=0;i<obj.children().length;i++){
                let child = obj.children()[i]
                textInfo.child.push(getAllText(child))
            }
        }
    } catch (error) {
        
    }

    return textInfo;
}


printAll()


function HomeInput(){
    // 如果在首页
    if (f.ms({ text: '首页' }) && f.ms({ text: '我' })){
        f.ms({desc:"搜索"}, true, 3)
    }

    if( f.ms({text:'猜你想搜'}) &&  f.ms({text:'历史记录'}) ){
        log('准备搜索界面')
        log('填入内容')
        setText(0, appInfo.searchKey)
        sleep(2000)
        f.ms({text: '搜索'}, true, 5)
    }

    if (f.ms({ text: '全部' }) && f.ms({ textMatches:'账号|用户'}) && f.ms({text:'商品'}) && !f.ms({text:'收起'}) ){
        log('搜索结果界面')
        f.ms({text:'全部'}, true, 2)
    }

    if (f.ms({ text: '全部' }) && f.ms({ textMatches:'账号|用户'}) && f.ms({text:'商品'}) && f.ms({text:'收起'})){
        log('搜索结果界面')
        // f.ms({text:'最新'}, true, 2)
        f.ms({text:'图文'}, true, 2)
        f.ms({text:'一周内'}, true, 2)
        f.ms({text:'收起'}, true, 8)
        this.search = true
    }
}



var usedtitle = []
var local = storages.create("xhs")
usedtitle = local.get('usedtitle') || []
// 增加弹窗提示，询问是否清理 usedtitle 以便重新开始累积
if (usedtitle.length > 0) {
    let clear = dialogs.confirm("清理提示", "是否清除已记录的标题usedtitle？\n（清除后将重新开始累积）");
    if (clear) {
        usedtitle = [];
        local.remove('usedtitle');
        toast("已清除usedtitle记录");
    } else {
        toast("保留原有usedtitle记录");
    }
}

usedtitle = local.get('usedtitle') || []


function click_title(){
    let title = textMatches(/.{10,999}/).find();
    if( title ){
        log( title.length )
        for (let index = 0; index < title.length; index++) {
            log( title[index].text() )
            if( !usedtitle.includes(title[index].text())  ){
                usedtitle.push(title[index].text())
                // f.clickObj(title[index], 3, 'title')
                f.clickTrue(title[index], 3, 'title', 5)  //换穿透点击
                appInfo.title = title[index].text()
                return true
            }
        }
    }
}

function page(){
    var auther = id("nickNameTV").findOne(200);
    if( auther ){
        log("作者:", auther.text() )
        appInfo.auther = auther.text()
    }else{
        return 
    }

    var content = textMatches(/[\s\S]{40,}/).findOne(200);
    if(content){
        log("content:", content.text() )
        appInfo.content = content.text()    
    }else{
        log('没有找到 content')
    }

    var objs = descMatches(/点赞.*/).findOne(200)
    if( objs ){
        log(objs.desc())
        // 提取数字部分
        var num = objs.desc().match(/\d+/g)
        appInfo.likes = num ? num.join('') : 0
    }
    var objs = descMatches(/收藏.*/).findOne(200)
    if( objs ){
        log(objs.desc())
        var num = objs.desc().match(/\d+/g)
        appInfo.fav = num ? num.join('') : 0
    }
    var objs = descMatches(/评论 .*/).findOne(200)
    if( objs ){
        log(objs.desc())
        var num = objs.desc().match(/\d+/g)
        appInfo.comment = num ? num.join('') : 0
    }

    if(f.ms({id:'moreOperateIV'}, true, 2)){
        f.ms({ text: '复制链接'}, true, 2)

        f.active("org.fd.ffdd.v7", 3)
        var link = getClip()
        if (link){
            log('获取到链接', link)
            appInfo['link'] = link
        }
        f.active("com.xingin.xhs", 3)
    }

    let postData = {
        title: appInfo.title,
        searchKey: appInfo.searchKey,
        auther: appInfo.auther,
        content: appInfo.content,
        link: appInfo.link,
        likes: appInfo.likes,
        fav: appInfo.fav,
        comment: appInfo.comment,
    }
    f.postJson(postData)
    local.put('usedtitle', usedtitle)
    return true
}




function getComment(){
    if ( f.ms({ desc:'评论框'})){
        log('在 page 页面')
        
        if( f.ms({textMatches:"展开.*回复", boundsInside:`0,0,${width},${height}` }, true, 1)){
            return 
        }


        var obj = textMatches(/.*回复/).find()
        if( obj){
            for (let index = 0; index < obj.length; index++) {
                let element = obj[index];
                // log(element.text())
                // log( JSON.stringify(getAllText(element.parent().parent())) )
    
                // 遍历嵌套对象，收集所有text字段
                function collectAllText(obj, arr) {
                    if (!arr) arr = [];
                    if (typeof obj === 'object' && obj !== null) {
                        if (obj.hasOwnProperty('text') && obj.text) {
                            arr.push(obj.text);
                        }
                        if (obj.hasOwnProperty('child') && Array.isArray(obj.child)) {
                            for (let i = 0; i < obj.child.length; i++) {
                                collectAllText(obj.child[i], arr);
                            }
                        }
                    }
                    return arr;
                }
                
                let allText = collectAllText(getAllText(element.parent().parent())).join('|');
                log(allText);

                let postData = {
                    page_id: appInfo.page_id,
                    comment: allText
                }
                f.postJsonc(postData)
            }
        }
        
        if( f.ms({textMatches:"- 到底了 -|抢首评"})){
            return true
        }else{
            f.moveTo(0.5,0.8,0.5,0.9, 800)
            f.moveTo(0.5,0.8,0.5,0.2, 800)
        }
    }else{
        return true
    }
}


appInfo.searchKey = "高尔夫搭子"

f.active("com.xingin.xhs", 3)

for (let index = 0; index < 90; index++) {

    if (f.ms({ text: '首页' }) && f.ms({ text: '我' })){
        HomeInput()
    }else{
        if(!this.search){
            back()
            log('回退一次')
            sleep(2000)
        }
    }

    if( this.search ){
        if( click_title() ){
            if( page() ){
                while (!getComment() ){
                    sleep(1000)
                }
                back()
                sleep(2000)
            }
        }else{
            f.moveTo(0.5,0.8,0.5,0.9, 800)
            f.moveTo(0.5,0.8,0.5,0.2, 800)
        }
    }
}


// log(f.getRealUrl('http://xhslink.com/m/4tT5gUozAie'))





